import MPageContainer from '@/components/MPageContainer';
import MQueryTable from '@/components/MQueryTable';
import type { FieldProps } from 'sula/es/form/Field';
import type { ColumnProps } from 'sula/es/table/Table';
import type { RenderCtx } from 'sula/es/types/plugin';
import { getProgramListConfig, excute, getScriptResult } from './service'
import { Button, Card, Divider, Drawer, Tag, Tooltip } from 'antd';
import React, { useState } from 'react';
import styles from './styles.less'
import { CheckCircleOutlined, CloseCircleOutlined, FullscreenOutlined, InfoCircleOutlined, PlayCircleOutlined, SmileTwoTone, SwapOutlined, SyncOutlined } from '@ant-design/icons';
import Editor from './component/editor'
import FullScreen from '@/components/FullScreen';
// import sqlFormatter from 'sql-formatter';
import qs from 'qs'
import { render } from 'react-dom';


const Contract: React.FC = () => {

    const [visible, setVisible] = useState(false)
    const [showQuestion, setShowQuestion] = useState('')
    const [value, setValue] = useState('')
    const [isRight, setIsRight] = useState(false)
    const [questionId, setQuestionId] = useState()
    const [status, setStatus] = useState(9)
    const [run, setRun] = useState(false)


    // 改变主题
    const handleThemeChange = () => {
        setIsRight(!isRight);
    };

    // 全屏功能
    const [isSqlIdeFullScreen, setIsSqlIdeFullScreen] = useState<boolean>(false);
    const handleFullScreenSqlIde = () => {
        setIsSqlIdeFullScreen(true);
    };
    const handleNormalScreenSqlIde = () => {
        setIsSqlIdeFullScreen(false);
    };

    const onCancel = () => {
        setVisible(false);
        setValue('')
    }

    const getResult = async (id: any) => {
        const res = await getScriptResult(id)
        if (res.code === 300) {
            setTimeout(() => {
                getResult(id)
            }, 1000)
            setStatus(6)
        }
        console.log(res, 'ooooo');
        if (res?.code === 200) {
            setStatus(res.data[0] ? res.data[0].runnerResult.code : '')
        }
    }

    const renderResult = () => {
        let icon;
        if (status === 0) {
            icon = <CheckCircleOutlined className={styles.taskSuccessIcon} />
            return (
                <>
                    {icon}
                    <Tag color={'green'}>运行成功</Tag>
                </>
            );
        }
        else if (status === 1) {
            icon = <CloseCircleOutlined className={styles.taskFailIcon} />;
            return (
                <>
                    {icon}
                    <Tag color={'red'}>编译失败</Tag>
                </>
            );
        }
        else if (status === 2) {
            icon = <CloseCircleOutlined className={styles.taskFailIcon} />;
            return (
                <>
                    {icon}
                    <Tag color={'red'}>运行超时</Tag>
                </>
            );
        }
        else if (status === 3) {
            icon = <CloseCircleOutlined className={styles.taskFailIcon} />;
            return (
                <>
                    {icon}
                    <Tag color={'red'}>运行时错误</Tag>
                </>
            );
        }
        else if (status === 4) {
            icon = <CloseCircleOutlined className={styles.taskFailIcon} />;
            return (
                <>
                    {icon}
                    <Tag color={'red'}>超过内存</Tag>
                </>
            );
        }
        else if (status === 5) {
            icon = <CloseCircleOutlined className={styles.taskFailIcon} />;
            return (
                <>
                    {icon}
                    <Tag color={'red'}>输出超出</Tag>
                </>
            );
        }
        else if (status === 6) {
            icon = <SyncOutlined className={styles.taskIcon} spin />;
            return (
                <>
                    {icon}
                    <Tag color={'blue'}>运行中</Tag>
                </>
            );
        }
        else if (status === -1) {
            icon = <CloseCircleOutlined className={styles.taskFailIcon} />;
            return (
                <>
                    {icon}
                    <Tag color={'red'}>非法操作</Tag>
                </>
            );
        }
        else if (status === 100) {
            icon = <CloseCircleOutlined className={styles.taskFailIcon} />;
            return (
                <>
                    {icon}
                    <Tag color={'red'}>调用异常</Tag>
                </>
            );
        } else {
            return (
                <>
                    <Tag color={'blue'}>等待运行</Tag>
                </>
            );
        }
    }

    const excuteScript = async () => {
        const obj = {
            code: value,
            questionId: questionId
        }
        const res = await excute(qs.stringify(obj))
        if (res.code === 200) {
            getResult(res.data.codeId)
            console.log(res.data.codeId, 'res.data.codeId');
        }
        // console.log(res, 'resres');
    }

    // const formatSQL = () => {
    //     const formatValue = sqlFormatter.format(value);
    //     // eslint-disable-next-line no-param-reassign
    //     setValue(formatValue)
    // };


    const fields = [
        {
            name: 'keyword',
            label: '关键词',
            field: {
                type: 'input',
                props: {
                    placeholder: '请输入关键字进行查询',
                    allowClear: true,
                    // type: 'number',
                },
            },
        },
    ];

    const columns = [
        {
            key: 'type',
            title: '题目类型',
            render: () => {
                return <Tag color={'green'}>编程题</Tag>
            },
            width: 80
        },
        {
            key: 'content',
            title: '题目内容',
            render: ({ record }: RenderCtx) => {
                const content = JSON.parse(record.content)
                return <pre>{content.body}</pre>
            }
        },
        {
            key: 'operator',
            title: '操作',
            width: 120,
            render: [
                {
                    type: 'link',
                    props: {
                        children: '进入答题',
                    },
                    action: [
                        ({ record }: RenderCtx) => {
                            const content = JSON.parse(record.content)
                            setQuestionId(record.questionId)
                            setVisible(true);
                            setShowQuestion(content.body.replace(/\n/g, "<br/>"))
                        },
                    ],
                },
            ],
        },
    ];


    return (
        <>
            <MPageContainer>
                <MQueryTable
                    rowKey="questionId"
                    columns={columns as ColumnProps[] & never[]}
                    remoteDataSource={getProgramListConfig()}
                    fields={fields as FieldProps[] & never[]}
                />
            </MPageContainer>
            <Drawer
                title="编程题库"
                visible={visible}
                onClose={onCancel}
                width="100%"
                bodyStyle={{
                    background: '#f0f0f0'
                }}
                className={styles.main}
            >
                <Card className={styles.firstCard}>
                    <Tag color={'blue'} className={styles.tag}><img src={require('../../../images/question.svg')} className={styles.icon} />
                        <span className={styles.font}>编程题 - 题目</span></Tag>
                    <div dangerouslySetInnerHTML={{ __html: showQuestion }}></div>
                </Card>
                <Card>
                    <div className={styles.sqlOprBar}>
                        <Tooltip title="执行脚本">
                            <Button
                                type="primary"
                                shape="round"
                                icon={<PlayCircleOutlined />}
                                size={'small'}
                                className={
                                    styles.sqlOprBtn
                                }
                                onClick={excuteScript}
                            >
                                运行代码
                           </Button>
                        </Tooltip>
                        <Tooltip title="全屏">
                            <FullscreenOutlined className={styles.sqlOprIcon}
                                onClick={handleFullScreenSqlIde}
                            />
                        </Tooltip>
                        {/* <Tooltip title="格式化语句">
                            <EditOutlined className={styles.sqlOprIcon}
                                onClick={formatSQL}
                            />
                        </Tooltip> */}
                        <Tooltip title="改变主题">
                            <SwapOutlined className={styles.sqlOprIcon} onClick={handleThemeChange} />
                        </Tooltip>
                        <span className={styles.run}><SmileTwoTone /> 运行结果：{renderResult()}</span>
                        <FullScreen
                            isFullScreen={isSqlIdeFullScreen}
                            // top={`${DEFAULT_FULLSCREEN_TOP}px`}
                            triggerBackToNormal={handleNormalScreenSqlIde}
                        >
                            <Editor
                                value={value}
                                onChange={setValue}
                                isRightTheme={isRight}
                            />
                        </FullScreen>
                    </div>
                </Card>
            </Drawer>
        </>
    );
};

export default Contract;
